package com.wx.house.manager.api.expenses.controller;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.wx.house.common.annotations.Paging;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageInfo;
import com.wx.house.manager.api.building.service.BBuildingRoomService;
import com.wx.house.manager.api.contract.service.CContractService;
import com.wx.house.manager.api.expenses.service.ECollectFeesService;
import com.wx.house.manager.api.expenses.service.ECostDetailService;
import com.wx.house.manager.api.expenses.service.ECostService;
import com.wx.house.manager.api.expenses.service.MeterReadingService;
import com.wx.house.manager.api.expenses.test.MeterReadingGet;
import com.wx.house.manager.api.expenses.test.MeterReadingModify;
import com.wx.house.manager.api.expenses.test.MeterReadingPame;
import com.wx.house.manager.api.expenses.test.MeterReadingUpdate;
import com.wx.house.manager.api.expenses.test.meterIdPame;
import com.wx.house.common.base.BaseController;
import com.wx.house.common.exception.BusinessException;
import com.wx.house.common.util.IDUtils;
import com.wx.house.common.util.JwtUtils;
import com.wx.house.core.pojo.base.BasePage;
import com.wx.house.core.pojo.base.Result;
import com.wx.house.core.pojo.base.UserInfo;
import com.wx.house.core.pojo.po.ECost;
import com.wx.house.core.pojo.po.ECostDetail;
import com.wx.house.core.pojo.po.MeterReading;
import com.wx.house.core.pojo.po.building.BuildingRoom;
import com.wx.house.core.pojo.vo.ContractBaseVo;
import com.wx.house.core.pojo.vo.MeterReadingVo;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("SysMenus/")
@Api(value = "抄表模块", tags = "模块:抄表管理")
@Slf4j
public class MeterReadingController extends BaseController{
	@Resource
	private MeterReadingService meterReadingService;
	@Resource 
	private ECostDetailService eCostDetailService;
	@Resource
	private CContractService cContractService;
	@Resource
	private BBuildingRoomService bBuildingRoomService;
	@Resource 
	private ECostService eCostService;
	
	
	@ApiOperation(value = "新增抄表", notes = "新增抄表")
	@PostMapping("addMeter/")
	public Result addMeter(@RequestBody @Validated MeterReadingPame meterReadingPame, HttpServletRequest request) {
		try {
			if(!ObjectUtils.isEmpty(meterReadingService.selectNumberMonth(meterReadingPame.getContrNumber(), meterReadingPame.getMonth()))) {
				return Result.error("当月已抄表");
			}
			MeterReading meterReading=MeterReading.builder()
					.id(IDUtils.genItemId(8)+"")
					.buildingId(meterReadingPame.getBuildingId())
					.doorNumber(meterReadingPame.getDoorNumber())
					.contrNumber(meterReadingPame.getContrNumber())
					.tenantName(meterReadingPame.getTenantName())
					.phone(meterReadingPame.getPhone())
					.month(meterReadingPame.getMonth())
					.monthWater(meterReadingPame.getMonthWater())
					.monthElectric(meterReadingPame.getMonthElectric())
					.monthGas(meterReadingPame.getMonthGas())
					.monthState(0)
					.build();
			meterReadingService.addMeter(meterReading);
			return Result.success();
		} catch (Exception e) {
			throw new BusinessException("添加失败");
		}
	}
	
	@ApiOperation(value = "查询抄表", notes = "查询抄表")
	@GetMapping("SelectMeter/")
	@Paging
	public Result<List<MeterReadingVo>> SelectMeter(@Validated MeterReadingGet meterReadingGet,BasePage page) {
		try {
			UserInfo userInfo = this.userInfo();
			List<MeterReadingVo> readingDtos=null;
			readingDtos =meterReadingService
						.AllMeter(meterReadingGet.getBuildName(), meterReadingGet.getMonth(),meterReadingGet.getMonthState(),userInfo.getMAccId());
			return Result.success(readingDtos);
		} catch (Exception e) {
			throw new BusinessException("查询失败");
		}
	}
	
	@ApiOperation(value = "抄表", notes = "抄表")
	@PutMapping("updateMeter/")
	public Result updateMeter(@RequestBody @Validated MeterReadingUpdate meterReadingUpdate) {
		try {
			MeterReading meterReading=MeterReading.builder()
					.id(meterReadingUpdate.getId())
					.monthWater(meterReadingUpdate.getMonthWater())
					.monthElectric(meterReadingUpdate.getMonthElectric())
					.monthGas(meterReadingUpdate.getMonthGas())
					.build();
			meterReadingService.updateMeter(meterReading);
			return Result.success();
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("抄表失败");
		}
	}
	
	@ApiOperation(value = "完成抄表", notes = "完成抄表")
	@PostMapping("Addcomplete/")
	public Result Addcomplete(@RequestBody @Validated meterIdPame meterIdPame) {
		try {
			if(meterIdPame.getMonthWater()==0) {
				return Result.error("水表读数为0，请输入输入水表读数");
			}
			if(meterIdPame.getMonthElectric()==0) {
				return Result.error("电表读数为0，请输入输入电表读数");			
			}
			if(meterIdPame.getMonthGas()==0) {
				return Result.error("气表读数为0，请输入输入气表读数");			
			}
			meterReadingService.addcompleteMeter(meterIdPame);
			return Result.success();
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("完成抄表失败");
		}
	}
	@ApiOperation(value = "修改抄表", notes = "修改抄表")
	@PutMapping("ModifyMeter/")
	public Result ModifyMeter(@RequestBody @Validated MeterReadingModify meterReadingModify) {
		try {
			//step1. 根据合同编号查询缴费状态
			ECostDetail eCostDetail = eCostDetailService.selectMonth(meterReadingModify.getContrNumber(),
					meterReadingModify.getFeeMonth(), meterReadingModify.getFeesType());
			ECost eCost=eCostService.selectId(eCostDetail.getECostId());
			if (!ObjectUtils.isEmpty(eCostDetail)) {
				if (eCostDetail.getCostState() == 1) {
					return Result.error("已收费,不能修改");
				}
			}
			//step2. 根据id抄表数据
			MeterReading meterReading= meterReadingService.getById(meterReadingModify.getId());
			//判断房间读数历史信息
			BuildingRoom buildingRoom=bBuildingRoomService.selectNumberRoom(meterReadingModify.getContrNumber());
			//step3. 查询合同数据
			ContractBaseVo contractBaseVo = cContractService.selectIdBase(meterReadingModify.getContrNumber());
			//step4. 根据历史读数减去现有读数判断读数数据是否正常
			Integer a=buildingRoom.getHistoryWater()-meterReading.getSameWater();//水
			Integer b=buildingRoom.getHistoryElectric()-meterReading.getSameElectric();//电
			Integer c=buildingRoom.getHistoryGas()-meterReading.getSameGas();//气
			//step5. 根据传过来的值判断修改值是否正常
			if ("3".equals(meterReadingModify.getFeesType())) {
				if(a>=meterReadingModify.getMonthvalue()) {
					return Result.error("读数过小,历史读数为"+a);
				}
				meterReading.setMonthWater(meterReadingModify.getMonthvalue());
				meterReading.setSameWater(meterReadingModify.getMonthvalue()-a);
				buildingRoom.setHistoryWater(meterReadingModify.getMonthvalue());
				if(a>=meterReadingModify.getMonthvalue()) {
					eCost.setTotal(eCost.getTotal().subtract(eCostDetail.getReceiveMoney()));
					eCostDetail.setReceiveMoney(big(meterReading.getSameWater()).multiply(contractBaseVo.getBuildWater()));
					eCost.setTotal(eCost.getTotal().add(eCostDetail.getReceiveMoney()));
				}
			} 
			if ("4".equals(meterReadingModify.getFeesType())) {
				if(b.compareTo(meterReadingModify.getMonthvalue())==1) {
					return Result.error("读数过小,历史读数为"+b);
				}
				meterReading.setMonthElectric(meterReadingModify.getMonthvalue());
				meterReading.setSameElectric(meterReadingModify.getMonthvalue()-b);
				buildingRoom.setHistoryElectric(meterReadingModify.getMonthvalue());
				if(a.compareTo(meterReadingModify.getMonthvalue())!=0) {
					eCost.setTotal(eCost.getTotal().subtract(eCostDetail.getReceiveMoney()));
					eCostDetail.setReceiveMoney(big(meterReading.getSameElectric()).multiply(contractBaseVo.getBuildElectric()));
					eCost.setTotal(eCost.getTotal().add(eCostDetail.getReceiveMoney()));
				}
			}
			if ("5".equals(meterReadingModify.getFeesType())) {
				if(c.compareTo(meterReadingModify.getMonthvalue())==1) {
					return Result.error("读数过小,历史读数为"+b);
				}
				meterReading.setMonthGas(meterReadingModify.getMonthvalue());
				meterReading.setSameGas(meterReadingModify.getMonthvalue()-c);
				buildingRoom.setHistoryGas(meterReadingModify.getMonthvalue());
				if(a.compareTo(meterReadingModify.getMonthvalue())!=0) {
					eCost.setTotal(eCost.getTotal().subtract(eCostDetail.getReceiveMoney()));
					eCostDetail.setReceiveMoney(big(meterReading.getSameGas()).multiply(contractBaseVo.getBuildGas()));
					eCost.setTotal(eCost.getTotal().add(eCostDetail.getReceiveMoney()));
				}
			}
			meterReadingService.updateMeterReading(meterReading, buildingRoom,eCostDetail,eCost);
			return Result.success();
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("修改抄表记录失败");
		}
	}
	
	/***
	 * Int转Big
	 * @param i
	 * @return
	 */
	private BigDecimal big(Integer i) {
		return new BigDecimal(Integer.toString(i));
	}
}
